import Vue from 'vue'
import Vuex from 'vuex'
import mutations from "./mutations"
import { ADD_COUNTER, ADD_TO_CART } from './mutationsType'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cartList: []
  },
  mutations,
  actions: {
    addCart(context, data) {
      let oldProduct = null
      // 判断商品数组中是否有已添加的商品，oldProduct为数组中的某商品对象
      // for (let item of state.cartList) {
      //   if (item.iid === data.iid) {
      //     oldProduct = item
      //   }
      // }
      oldProduct = context.state.cartList.find(item => item.iid == data.iid)
      console.log('cartList', context.state.cartList);
      // 如果有数量加1
      if (oldProduct) {
        context.commit(ADD_COUNTER, oldProduct)
      } else {
        data.count = 1
        context.commit(ADD_TO_CART, data)
      }
    }
  },
  getters: {
    cartLength(state) {
      return state.cartList.length
    },
    cartList(state) {
      return state.cartList
    }
  },
  modules: {
  }
})
